using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using Kingdee.BOS.Util;
using Kingdee.BOS;
using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.Metadata;


namespace CZ.PAEZ.SaleManager.ServicePlugIns
{
    /// <summary>
    /// 该插件已弃用
    /// </summary>
    [Description("收料通知单审核插件")]
    [HotUpdate]
    public class ReceiveBillAudit : AbstractOperationServicePlugIn
    {
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);
            foreach(var dataEntity in e.DataEntitys)
            {
                string fid = dataEntity["Id"].ToString();
                // 审核后生成内外部批号映射单
                string sql = string.Format(@"/*dialect*/
select r.FDate, rs.FSrMaterialId, lm.FNumber FLotNo, rs.FSRSUPPLYLOT 
from (
    select FID, FDate from T_PUR_Receive where FID={0}
) r
inner join T_PUR_ReceiveEntry re on re.FID=r.FID
inner join T_PUR_RECEIVESERIAL rs on re.FENTRYID=rs.FENTRYID and rs.FSRSUPPLYLOT<>''
inner join t_bd_LotMaster lm on lm.FLotId=rs.FSRLOT
left join PAEZ_BD_LotMap lmp on lmp.FMATERIALID=rs.FSRMATERIALID 
    and lmp.FSUPPLIERLOT=rs.FSRSUPPLYLOT and lmp.FMTLLOT=lm.FNUMBER
where isnull(lmp.FID, 0)=0", fid);
                var entry = DBUtils.ExecuteDynamicObject(Context, sql);
                if(entry.Count <= 0) return;
                
                var meta = ServiceHelper.GetService<IMetaDataService>().Load(Context, "PAEZ_BD_LotMap") as FormMetadata;
                var model = new List<DynamicObject>();
                foreach(var row in entry)
                {
                    var data = new DynamicObject(meta.BusinessInfo.GetDynamicObjectType());
                    data["FCreateDate"] = DateTime.Today.ToString();
                    data["FMaterialId_Id"] = row["FSrMaterialId"].ToString();
                    data["FMtlLot"] = row["FLotNo"].ToString();
                    data["FSupplierLot"] = row["FSRSUPPLYLOT"].ToString();
                    data["FPurchaseDate"] = row["FDate"].ToString();
                    data["FExpiriedDate"] = "2099-12-31";
                    model.Add(data);
                }
                if(model.Count > 0)
                {
                    ServiceHelper.GetService<ISaveService>().Save(Context, meta.BusinessInfo, model.ToArray());
                }
            }
            
        }
    }
}
